<style>
.tree {
  /*margin-top: 42px;*/
  border: 1px solid #d7dde4;
  height: 600px;
}

.ztree li span {
  padding-bottom: 25px;
  /*margin-top: 20px;*/
  /*margin-bottom: 20px;*/
  /*border: 1px solid #ffffff;*/
  /*background: #f0f6e4;*/
  /*width:220px;height:360px;*/
  /*overflow-y:scroll;*/
  /*overflow-x:auto;*/
}
</style>

<template>
<Row class="layout-content-body">
  <Col span="4" class="tree">
  <div class="bg left">
    <ul id="treeD" class="ztree"></ul>
  </div>
  </Col>
  <Col span="20">
  <dtable :columns="columns" :dataAll="dataAll" :dataShow="dataShow" :loading="loading" add delCheck assign check op @refresh="getall()" @add="add" @del="del" @edit="edit" @delCheck="delCheck" @assign="assign"></dtable>
  </Col>
  <Modal title="部门信息" v-model="editData" :mask-closable="false" class="editm" @on-ok="asyncOK" @on-cancel="asyncCancel">
    <Form ref="editForm" :model="formItem" :label-width="80" :rules="ruleValidate">
      <Form-item label="名称" prop="Name">
        <Input v-model="formItem.Name" placeholder="请输入" @on-enter="asyncOK()"></Input>
      </Form-item>
      <Form-item label="所属单位" prop="OrgId">
        <Select v-model="formItem.OrgId" disabled placeholder="请选择">
            <Option v-for="item  in dataAll" :value="item.OrgId" :key="item.OrgId">{{item.OrgName}}</Option>
          </Select>
      </Form-item>
      <Form-item label="上级部门" prop="Pid">
        <Select v-model="formItem.Pid" placeholder="请选择">
            <Option v-for="item  in parentRes" :value="item.Id" :key="item.Id">{{item.Name}}</Option>
          </Select>
      </Form-item>
      <Form-item label="状态" prop="Status">
          <Radio-group v-model.number="formItem.Status" disabled>
            <Radio label="1">启用</Radio>
            <Radio label="0">停用</Radio>
          </Radio-group>
        </Form-item>
      <Form-item label="说明" prop="Remark">
        <Input v-model="formItem.Remark" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入...">
        </Input>
      </Form-item>
    </Form>
  </Modal>
</Row>
</template>

<script>
import api from '../../api'
import '../../../static/plugins/zTree/js/jquery.ztree.core'
import '../../../static/plugins/zTree/js/jquery.ztree.excheck'
import '../../../static/plugins/zTree/js/jquery.ztree.exedit'
import '../../../static/plugins/zTree/js/jquery.ztree.exhide'
import 'font-awesome/css/font-awesome.css'
import '../../../static/plugins/zTree/css/awesomeStyle/awesome.css'
import {
  mapMutations,
  mapGetters,
  mapState
} from 'vuex'
import dtable from '../../components/table/dtable.vue' //采用biztable
export default {
  data() {
    return {
      loading: false, //数据刷新遮罩层
      columns: [{
          title: '名称',
          key: 'Name',
          sortable: true
        },
        {
          title: '上级部门',
          key: 'Pname',
        },
        {
          title: '所属单位',
          key: 'OrgName',
          width: 280,
          sortable: true
        },
        {
          title: '状态',
          key: 'Sname',
          sortable: true,
        },
      ], //表格样式
      dataAll: [], //表格数据来源
      dataShow: true, //是否显示表格数据查看表单
      editData: false, //显示编辑表单
      formItem: {
        Name: '',
        Pid: 0,
        Pname: '顶级部门',
        OrgId: '',
        OrgName: '',
        Status: 1,
        Remark: ''
      }, //数据编辑表单
      ruleValidate: {
        Name: [{
          required: true,
          message: '账号不能为空',
          trigger: 'blur'
        }],
        Pname: [{
          required: true,
          message: '名称不能为空',
          trigger: 'blur'
        }, ],
        //          Pid: [
        //            {required: true, message: '必须选择上级部门', trigger: 'change'},
        //          ],
      }, //数据编辑表单验证规则
      addid: true, //true为修改模式，false为添加模式
      treeData: [],
      total: 0,
      setting: {
        view: {
          selectedMulti: false
        },
        check: {
          enable: false
        },
        data: {
          simpleData: {
            enable: true,
            rootPId: 0
          }
        },
        edit: {
          enable: true,
          showRemoveBtn: false,
          showRenameBtn: false
        },
        callback: {
          beforeDrag: this.beforeDrag,
          beforeDrop: this.beforeDrop
        }
      },
      zNodes: []
    }
  },
  components: {
    dtable,
  },
  computed: {
    // ...mapState(['isLogin', 'captchaUrl', 'cptId', 'msg', 'userInfo']),
    state() {
      return this.$store.state.app
    },
    //      父部门
    parentRes() {
      let pr = []
      pr.push({
        Id: 0,
        Name: "顶级部门"
      })
      for (let e in this.dataAll) {
        pr.push({
          Name: this.dataAll[e].Name,
          Id: this.dataAll[e].Id
        })
      }
      return pr
    },
  },
  watch: {},
  methods: {
    beforeDrop(treeId, treeNodes, targetNode, moveType) {
      return targetNode ? targetNode.drop !== false : true;
    },
    beforeDrag(treeId, treeNodes) {
      for (var i = 0, l = treeNodes.length; i < l; i++) {
        if (treeNodes[i].drag === false) {
          return false;
        }
      }
      return true;
    },
    //      改变页码
    getall() {
      this.loading = true
      this.$api.GetDept().then(res => {
        if (!res.error) {
          this.dataAll = res.Data.tabledata
          this.total = this.dataAll.length
          this.zNodes = res.Data.treedata
          $.fn.zTree.init($("#treeD"), this.setting, this.zNodes)
        } else {
          this.$Message.error(res.message)
        }
      }, error => {
        this.$Message.error(res.message, 4)
      })
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    getOrganization() {
      this.spinShow = true
      this.$api.getOrganizationList().then(res => {
        if (!res.error) {
          this.org = res.Data
        } else {
          this.$Message.error(res.message)
        }
      }, err => {
        this.$Message.error(res.message, 4)
      })
    },
    edit(index) {
      this.addid = true
      this.formItem = index
      this.editData = true
    },
    add() {
      this.addid = false
      this.$refs['editForm'].resetFields()
      this.formItem.OrgId = this.state.userInfo.Organization.Id
      this.editData = true
    },
    asyncOK() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          if (this.addid) {
            this.$api.UpdateDept(this.formItem).then(res => {
              if (!res.error) {
                this.getall()
                this.$Message.success(res.message)
              } else {
                this.$Message.error(res.message, 4)
              }
            }, err => {
              this.$Message.error(res.message, 4)
            })
          } else if (!this.addid) {
            this.$api.AddDept(this.formItem).then(res => {
              if (!res.error) {
                this.getall()
                this.$Message.success(res.message)
              } else {
                this.$Message.error(res.message, 4)
              }
            }, err => {
              this.$Message.error(res.message, 4)
            })
          }
          setTimeout(() => {
            this.editData = false;
          }, 1000);
        } else {
          this.$Message.error('表单验证失败!');
        }
      })
      this.editData = false
      this.$refs['editForm'].resetFields()

    },
    asyncCancel() {
      this.getall()
      this.$refs['editForm'].resetFields()
    },
    del(row) {
      this.$api.DeleteDept(row).then(res => {
        if (!res.error) {
          this.getall()
          this.$Message.success(res.message)
        } else {
          this.$Message.error(res.message, 4)
        }
      }, err => {
        this.$Message.error(res.message, 4)
      })
    },
    delCheck(row) {
      this.$api.DeleteDepts(row).then(res => {
        if (!res.error) {
          this.getall()
          this.$Message.success(res.message)
        } else {
          this.$Message.error(res.message, 4)
        }
      }, err => {
        this.$Message.error(res.message, 4)
      })
    },
    assign() {
      let treeObj = $.fn.zTree.getZTreeObj("treeD");
      let tee = treeObj.transformToArray(treeObj.getNodes());
      console.log(tee)
      this.$api.AssignUserDept(tee).then(res => {
        if (!res.error) {
          this.$Message.success(res.message)
        } else {
          this.$Message.error(res.message, 4)
        }
      }, err => {
        this.$Message.error(res.message, 4)
      })
    },

  },
  mounted() {
    let self = this
    this.getall()
    //      $(document).ready(function(){
    //        $.fn.zTree.init($("#treeDemo"), this.setting, this.znodes)
    //      })
    //      $(document).ready(function(){

    //        setCheck();
    //        $("#r1").bind("change", setCheck);
    //        $("#r2").bind("change", setCheck);
    //        $("#disablechk").bind("change", setCheck);
    //      });
  }
}
</script>
